# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 消费者代码：公平分发（加了 basic_qos）.py
# @Author: dongguangwen
# @Date  : 2025-04-12 18:40
import pika
import time


def callback(ch, method, properties, body):
    print(f"[⚖️] 接收到任务: {body.decode()}")
    time.sleep(2)  # 模拟耗时任务
    ch.basic_ack(delivery_tag=method.delivery_tag)


credentials = pika.PlainCredentials('admin', 'password')
connection = pika.BlockingConnection(
    pika.ConnectionParameters('192.168.1.119', credentials=credentials, virtual_host='my_vhost'))
channel = connection.channel()

channel.queue_declare(queue='task_queue', durable=True)

# 关键参数：每次只分配一个未处理完的消息
channel.basic_qos(prefetch_count=1)

channel.basic_consume(queue='task_queue', on_message_callback=callback)

print('[🚀] 等待消息（公平分发）...')
channel.start_consuming()
